﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ColorApplication.Helper;

namespace ColorApplication
{
    public partial class WebFile : mht
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["csvdatatable" + "1"] != null)
                {
                    DataTable csvdatatable = (DataTable)Session["csvdatatable" + "1"];
                    // Get Attribute Families 
                    SetAttributeFamilies(csvdatatable);
                    SetContributedColorTab(csvdatatable);
                    if (Session["imgFilename"] != null)
                    {
                        string filename = Session["imgFilename"].ToString();
                        Image1.ImageUrl = "~/UpldImage/" + filename;
                        ImageNameLabel.Text = filename.Remove(filename.LastIndexOf('.'));

                        // code to find size of the Image
                        getImageSize(Server.MapPath("~/UpldImage/") + filename);
                    }
                    //check query string to see whether request is for download or to view file.
                    if (Request.QueryString["download"] != null)
                    {
                        DownloadPage();
                        // Response.Clear();
                        //Response.Redirect("~/FileUpload.aspx");
                    }
                }

            }
        }

        private void getImageSize(string filePath)
        {
            // find size of the file
            string[] sizes = { "B", "KB", "MB", "GB" };
            int s = 0;
            long fileSize = new FileInfo(filePath).Length;
            while (fileSize >= 1024)
            {
                s++;
                fileSize /= 1024;
            }
            string fileSizeInfo = String.Format("( {0} {1} )", fileSize, sizes[s]);

            FileSizeLabel.Text = fileSizeInfo;
        }

        public void SetAttributeFamilies(DataTable csvdatatable)
        {
            // This is Create Color Table Temp
            DataTable colordt = new DataTable();
            colordt.Columns.Add("Color");
            foreach (DataRow row in csvdatatable.Rows)
            {

                int RCode = Convert.ToInt32(row["R value"].ToString());
                int GCode = Convert.ToInt32(row["G value"].ToString());
                int BCode = Convert.ToInt32(row["B value"].ToString());
                // Find Main Color
                string Color = GetcolorsinSubcolor(RCode, GCode, BCode);
                DataRow r = colordt.NewRow();
                r["Color"] = Color;
                colordt.Rows.Add(r);

            }

            DataTable tempdt = colordt.DefaultView.ToTable(true, "Color");

            DataTable attributedt = new DataTable();
            attributedt.Columns.Add("Attribute");
            // Calculated Color Percentage of Picture
            foreach (DataRow row in tempdt.Rows)
            {
                string ColorName = row["Color"].ToString();
                List<string> listofattribute = GetColorAttributesByColorName(ColorName);
                foreach (string attribute in listofattribute)
                {
                    DataRow attributerow = attributedt.NewRow();
                    attributerow["Attribute"] = attribute;
                    attributedt.Rows.Add(attributerow);

                }
            }

            DataTable attributefamiliesdt = attributedt.DefaultView.ToTable(true, "Attribute");
            DataTable attributeXAttributefamiliesdt = new DataTable();
            attributeXAttributefamiliesdt.Columns.Add("Attribute");
            attributeXAttributefamiliesdt.Columns.Add("Attribute Families");

            foreach (DataRow row in attributefamiliesdt.Rows)
            {
                string AttributeName = row["Attribute"].ToString();
                DataTable AttributesFamiliesdt = GetAttributesFamiliesByAttributeName(AttributeName);
                if (AttributesFamiliesdt != null)
                {
                    foreach (DataRow familiesrow in AttributesFamiliesdt.Rows)
                    {
                        DataRow attributeXAttributefamiliesrow = attributeXAttributefamiliesdt.NewRow();
                        attributeXAttributefamiliesrow["Attribute"] = familiesrow["Attribute"];
                        attributeXAttributefamiliesrow["Attribute Families"] = familiesrow["Attribute Families"];
                        attributeXAttributefamiliesdt.Rows.Add(attributeXAttributefamiliesrow);
                    }

                }

            }

            DataTable attributeXFamailiesTempdt = attributeXAttributefamiliesdt.DefaultView.ToTable(true, "Attribute Families");

            attributeXFamailiesTempdt.Columns.Add("Attribute");
            attributeXFamailiesTempdt.Columns.Add("Count", Type.GetType("System.Int32"));
            attributeXFamailiesTempdt.Columns.Add("Percentage", Type.GetType("System.Double"));
            attributeXFamailiesTempdt.Columns.Add("WeightedPercentage", Type.GetType("System.Double"));

            foreach (DataRow row in attributeXFamailiesTempdt.Rows)
            {
                string AttributeFamilies = row["Attribute Families"].ToString();
                DataTable AttributeList = GetAttribute(attributeXAttributefamiliesdt, AttributeFamilies);
                string attributestr = string.Empty;
                int AttributeCount = 0;
                double percentage = 0;
                DataTable ColorAttributedatatable = Session["ColorAttributedatatable" + "1"] as DataTable;
                foreach (DataRow dr in AttributeList.Rows)
                {
                    string atrbte = dr["Attribute"].ToString();
                    double totalofPercentage = GetColorTotalFamilyPercentage(ColorAttributedatatable, AttributeList);
                    double colorPercentage = GetColorPercentageofAttribute(ColorAttributedatatable, atrbte);
                    double attributePercentage = 0;
                    if (totalofPercentage > 0)
                    {
                        attributePercentage = (colorPercentage / totalofPercentage) * 100;
                    }
                    dr["Percentage"] = attributePercentage;
                }
                AttributeList.DefaultView.Sort = "Percentage DESC";
                AttributeList = AttributeList.DefaultView.ToTable();

                foreach (DataRow dr in AttributeList.Rows)
                {
                    AttributeCount++;
                    attributestr = attributestr + dr["Attribute"] + " " + String.Format("{0:00.00}", Math.Round(Convert.ToDouble(dr["Percentage"]), 2)) + "% </br>";

                    foreach (DataRow rw in ColorAttributedatatable.Rows)
                    {
                        if (rw["Attribute"].ToString().Equals(dr["Attribute"]))
                        {

                            percentage += Convert.ToDouble(rw["Color Area Percentage"]);
                        }
                    }

                }

                row["Attribute Families"] = row["Attribute Families"];
                row["Attribute"] = attributestr;
                row["Count"] = AttributeCount;
                row["Percentage"] = percentage;

            }

            attributeXFamailiesTempdt = CalculatedWeightedAttributeFamily(attributeXFamailiesTempdt);
            attributeXFamailiesTempdt.DefaultView.Sort = "Percentage DESC";
            Session["AttributeFamiliesdatatable"] = attributeXFamailiesTempdt;
            AttributeFamiliesGridView.DataSource = attributeXFamailiesTempdt.DefaultView;
            AttributeFamiliesGridView.DataBind();
        }
        //Shravankumar 
        /// <summary>
        /// Get Color Percentage ColorAttributedatatable
        /// </summary>
        /// <param name="ColorAttributedatatable"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        public double GetColorPercentageofAttribute(DataTable ColorAttributedatatable, string attribute)
        {
            double percentageofAttribute = 0;
            if (ColorAttributedatatable != null)
            {
                foreach (DataRow row in ColorAttributedatatable.Rows)
                {
                    if (row["Attribute"].ToString().Equals(attribute))
                    {
                        percentageofAttribute = Convert.ToDouble(row["Color Area Percentage"]);
                        return percentageofAttribute;
                    }
                }

            }
            return percentageofAttribute;
        }
        //Shravankumar 
        /// <summary>
        /// this method for calculated Total of attribute Percentage
        /// </summary>
        /// <param name="ColorAttributedatatable"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        public double GetColorTotalFamilyPercentage(DataTable ColorAttributedatatable, DataTable AttributeList)
        {
            double totalofPercentage = 0;
            if (ColorAttributedatatable != null)
            {
                foreach (DataRow attribute in AttributeList.Rows)
                {
                    foreach (DataRow row in ColorAttributedatatable.Rows)
                    {

                        if (row["Attribute"].ToString().Equals(attribute["Attribute"]) && Convert.ToDouble(row["Color Area Percentage"]) > 0)
                        {
                            totalofPercentage += Convert.ToDouble(row["Color Area Percentage"]);
                        }
                    }
                }

                return totalofPercentage;
            }
            return totalofPercentage;


        }
        //Shravankumar 
        /// <summary>
        /// This method Accept Parameter Datatable and Calculated WeightedPercentage for Attribute family
        /// </summary>
        /// <param name="attributeXFamailiesTempdt">DataTable</param>
        /// <returns>DataTable</returns>
        public DataTable CalculatedWeightedAttributeFamily(DataTable attributeXFamailiesTempdt)
        {
            if (attributeXFamailiesTempdt != null)
            {
                double totalofWeightPercentage = GetTotalofWeightedAttributeFamilyPercentage(attributeXFamailiesTempdt);

                foreach (DataRow row in attributeXFamailiesTempdt.Rows)
                {
                    if (Convert.ToDouble(row["Percentage"]) > 0 && totalofWeightPercentage > 0)
                    {
                        row["WeightedPercentage"] = (Convert.ToDouble(row["Percentage"]) / totalofWeightPercentage) * 100;
                    }
                }


            }
            return attributeXFamailiesTempdt;
        }
        //Shravankumar Get Total of Weighted Percentage of AttributeFamily 
        /// <summary>
        /// Accept DataTable attributeXFamailiesTempdt return totalofWeightPercentage
        /// </summary>
        /// <param name="attributeXFamailiesTempdt"></param>
        /// <returns></returns>
        public double GetTotalofWeightedAttributeFamilyPercentage(DataTable attributeXFamailiesTempdt)
        {
            double totalofWeightPercentage = 0;
            if (attributeXFamailiesTempdt != null)
            {
                foreach (DataRow row in attributeXFamailiesTempdt.Rows)
                {
                    if (Convert.ToDouble(row["Percentage"]) > 0)
                    {
                        totalofWeightPercentage += Convert.ToDouble(row["Percentage"]);
                    }
                }

                return totalofWeightPercentage;
            }
            return totalofWeightPercentage;


        }
        public string GetcolorsinSubcolor(int RCode, int GCode, int BCode)
        {
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters ={
                                            new SqlParameter("@RCode",RCode),
                                            new SqlParameter("@GCode",GCode),
                                            new SqlParameter("@BCode",BCode)};
                SqlCommand cmd = SQLHelper.GetCommand(con, "GetcolorsinSubcolor", parameters);
                con.Open();
                string Color = Convert.ToString(cmd.ExecuteScalar());
                con.Close();
                if (Color != string.Empty)
                {

                    return Color;
                }
                else
                {
                    return "Unknown Color";

                }
            }
        }

        public List<string> GetColorAttributesByColorName(string ColorName)
        {
            List<string> listofattribute = new List<string>();
            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@ColorName", ColorName) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetColorAttributesByColorName", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                // Get Attribute Name
                string AttributeName = dr["Description"].ToString();
                listofattribute.Add(AttributeName);

            }
            return listofattribute;

        }

        public DataTable GetAttributesFamiliesByAttributeName(string AttributeName)
        {

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@AttributeName", AttributeName) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetAttributesFamiliesByAttributeName", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();

            }
            return ds.Tables[0];
        }

        public DataTable GetAttribute(DataTable attributeXFamailiesdt, string AttributeFamilies)
        {

            DataTable AttributeList = new DataTable();
            AttributeList.Columns.Add("Attribute");
            AttributeList.Columns.Add("Percentage", typeof(double));

            if (attributeXFamailiesdt != null)
            {
                foreach (DataRow row in attributeXFamailiesdt.Rows)
                {
                    if (row["Attribute Families"].ToString() == AttributeFamilies)
                    {
                        DataRow dr = AttributeList.NewRow();
                        dr["Attribute"] = row["Attribute"].ToString();
                        AttributeList.Rows.Add(dr);
                    }
                }
            }
            return AttributeList;
        }

        private void DownloadPage()
        {
            if (Session["imgFilename"] != null)
            {
                string filename = Session["imgFilename"].ToString();
                string ext = filename.Substring(filename.LastIndexOf('.') + 1);
                ext.ToLower();

                mhtImageCollection oMhtCol = new mhtImageCollection();

                if (ext == "gif")
                {
                    oMhtCol.@add(new mhtImage(System.Drawing.Image.FromFile(Server.MapPath(filename)), filename, System.Drawing.Imaging.ImageFormat.Gif));
                }
                if (ext == "jpg")
                {
                    oMhtCol.@add(new mhtImage(System.Drawing.Image.FromFile(Server.MapPath(filename)), filename, System.Drawing.Imaging.ImageFormat.Jpeg));
                }
                if (ext == "jpeg")
                {
                    oMhtCol.@add(new mhtImage(System.Drawing.Image.FromFile(Server.MapPath(filename)), filename, System.Drawing.Imaging.ImageFormat.Jpeg));
                }
                if (ext == "png")
                {
                    oMhtCol.@add(new mhtImage(System.Drawing.Image.FromFile(Server.MapPath(filename)), filename, System.Drawing.Imaging.ImageFormat.Png));
                }
                if (ext == "bmp")
                {
                    oMhtCol.@add(new mhtImage(System.Drawing.Image.FromFile(Server.MapPath(filename)), filename, System.Drawing.Imaging.ImageFormat.Bmp));
                }

                sendMHTFile(convertWebControlToMHTString(this.Page, oMhtCol), filename + ".mht");
            }
            else
            {
                ErrorLabel.Text = "Please upload the Image again!";
            }
        }

        protected void AttributeFamiliesGridView_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemIndex == 2)
            {
                HtmlTableRow trSpace1 = (HtmlTableRow)e.Item.FindControl("trSpace1");
                HtmlTableRow trSpace2 = (HtmlTableRow)e.Item.FindControl("trSpace2");
                trSpace1.Visible = true;
                trSpace2.Visible = true;
            }
        }

        private void SetContributedColorTab(DataTable csvdatatable)
        {
            DataTable ColorAttributedatatable = Session["ColorAttributedatatable" + "1"] as DataTable;
            ColorAttributedatatable.DefaultView.Sort = "Color Area Percentage Desc";
            ColorAttributedatatable = ColorAttributedatatable.DefaultView.ToTable();
            DataTable Colordatatable = Session["Colordatatable" + "1"] as DataTable;
            int AttributeId = GetAttributeId(ColorAttributedatatable.Rows[0]["Attribute"].ToString());
            DataTable ColorsInAttribute = GetColorsByAttributes(AttributeId);
            DataTable result = new DataTable();
            result.Columns.Add("Color");
            result.Columns.Add("Percentage");
            string star = "<font style=\"color: red; font-weight: bold;\">*</font>";
            foreach (DataRow dr in ColorsInAttribute.Rows)
            {
                foreach (DataRow colordr in Colordatatable.Rows)
                {
                    if (dr["Color"].ToString() == colordr["Color"].ToString().Replace(star, string.Empty))
                    {
                        DataRow resultRow = result.NewRow();
                        resultRow["Color"] = colordr["Color"];
                        resultRow["Percentage"] = colordr["Percentage"];
                        result.Rows.Add(resultRow);
                    }
                }
            }
            result.DefaultView.Sort = "Percentage DESC";
            result = result.DefaultView.ToTable();
            LabelContributedColor.Text = "The color which contributed most to good direction is " + result.Rows[0]["Color"].ToString().Replace(star, string.Empty);
        }

        //Jayant Pawar
        public int GetAttributeId(string Description)
        {
            // This Function Check Record in Attribute Table For Dublicate Description Name Exist or Not
            // if Record Found Return true
            //else return false

            DataSet ds = new DataSet();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@Description", Description) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "CheckDescriptionExistinAttribute", parameters);
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(ds);
                con.Close();
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                return (int)dr["Id"];
            }

            return 0;

        }

        //Jayant Pawar
        public DataTable GetColorsByAttributes(int AttributeId)
        {

            SqlDataReader dr;
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection())
            {
                SqlParameter[] parameters = { new SqlParameter("@AttributeId", AttributeId) };

                SqlCommand cmd = SQLHelper.GetCommand(con, "GetSearchByColorsAttributeSelect", parameters);
                con.Open();
                dr = cmd.ExecuteReader();
                dt.Load(dr);
                con.Close();
                if (dt != null && dt.Rows.Count > 0)
                    return dt;
                return null;
            }
        }
    }

}